#include "client.h"
#include "message.h"


//TODO COMMANDE LSITER LES OCNNECTES

void* client_side(void* arg)
{
        char name[SIZENAME];
        int i, flag_alone=1;
        
        memset(name, '\0', SIZENAME);
        strcpy(name, (char*) arg);
        
        /* Welcome message */
        printf("* Welcome to Panda messenger, %s !\n", name);
        printf("<-- Connecting to PANDA Network... \n");

        
        send_message_all("", CONNECTION);
        
        sleep(1);
        for(i=0;i<adressBook.nbContacts; i++)
        {
                if(adressBook.contacts[i].connected)
                {
                        flag_alone=0;
                }
        }
        
        if (flag_alone)
        {
                printf("* Aucun contact connecté.\n");
        }
        
        // Boucle de demande d'un message du client
        int quit = 0;
        int cmdc;
        char raw[RAWSIZE];
        
        while (!quit)
        {
                cmdc = -1;
                // Prompt
                printf("> ");
                fflush(stdout);
                // On lit le texte que rentre l'utilisateur
                fgets(raw, RAWSIZE, stdin);
                // On parse le message reçu
                if (raw[0] != '\n')
                {                       
                        if (strcmp(raw, "/quit\n") == 0)
                        {
                                // On quitte
                                
                                send_message_all("", DECONNECTION);
                                
                                exit(0);
                        }
                        else
                        {
                                parse_message(raw);
                        }               
                }
                memset(raw,'\0',RAWSIZE);
                
        }
        
        return NULL;
}

void parse_message(char* raw)
{
        char name[RAWSIZE];
        char message[RAWSIZE];
        memset(name,'\0',RAWSIZE);
        memset(message,'\0',RAWSIZE);
        
        // Parsing: "@<name>: <message>"
        
        if (raw[0] != '@')
        {
                printf("Mauvais format : @<destinataire(s)>: <message>\n");
                return;
        }
        
        raw[strlen(raw)-1] = '\0';
        
        // Parsing du name
        int i; 
        for (i=0; i<(int)strlen(raw) && raw[i] != ':'; i++);
        
        if (i == (int)strlen(raw))
        {
                printf("Mauvais format : @<destinataire(s)>: <message>\n");
                return;
        }
        
        // TODO: virer les espaces du name
        memcpy(name, raw+1, i-1);
        name[i-1]='\0';
        memcpy(message, raw+i+1, (int)strlen(raw)-i);
        
        // Broadcast ?
        if (strcmp(name, "all") == 0)
        {               
                // On vérifie qu'il y'a bien des gens co (sinon c'est inutile)
                for (i=0; i<adressBook.nbContacts && adressBook.contacts[i].connected == 0; i++);
                        
                if (i == adressBook.nbContacts)
                {
                        printf("* Personne n'est connecté.\n");
                        return;
                }
        
                send_message_all(message, STANDARD);
                
                return;
        }
        
        // Nom de groupe ?
        for (i=0; i<adressBook.nbGroups; i++)
        {       
                // Si le nom du groupe correspond
                if (strcmp(adressBook.groups[i].groupName, name) == 0)
                {
                        // On envoie un message à tous ses membres
                        int j;
                        for (j=0; j<adressBook.groups[i].nbMembers; j++)
                        {
                                send_message_contact(adressBook.groups[i].members[j], message); 
                        }
                                
                        return;
                }
        }
        
        // Si le nom de contact existe
        if ((i = searchContactIndex(name))!=-1)
        {
                // Formulation du message
                Message msg;
                
                struct timeval tv;
                gettimeofday(&tv,NULL);
                msg.timestamp = tv.tv_sec;
                /* Message type */
                msg.type = STANDARD;
                /* Sender IP */
                strcpy(msg.ipSender, adressBook.me.ip);
                /* Sender name */
                strcpy(msg.nameSender, adressBook.me.name);
                /* Message contents */
                msg.size = strlen(message)+1;
                msg.message = malloc(RAWSIZE * sizeof(char));
                memset(msg.message, '\0', RAWSIZE);
                strcpy(msg.message,message);
                
                // On lui envoie un message
                Contact c = adressBook.contacts[i];
        
                if(c.connected)
                {
                        // Contact name
                        strcpy(msg.nameReceiver, c.name);
        
                        // Contact ip
                        strcpy(msg.ipReceiver, c.ip);
                        
                        /*
                        pthread_t id;
                        pthread_create(&id, NULL, send_message_thread, (void*)&msg);
                        */
                        
                        send_message(msg);
                }
                else
                {
                        printf("* %s n'est pas connecté\n",c.name);
                }
                return;
        }
        
        // Soi-même
        if (strcmp(name, adressBook.me.name) == 0)
        {
                printf(" ...\n# %s@%s : %s\n> ... ", name, name, message);
                fflush(stdout);
                return;
        }
        
        // On arrive ici, on a trouvé personne : on lance la recherche
        printf("* Destinataire '%s' inconnu - Lancement de la recherche\n", name);      
        
        Message search_msg;
        
        /* Timestamp */
        struct timeval tv;
        gettimeofday(&tv,NULL);
        search_msg.timestamp = tv.tv_sec;
        /* Message type */
        search_msg.type = SEARCH;
        /* Sender IP */
        strcpy(search_msg.ipSender, adressBook.me.ip);
        /* Sender name */
        strcpy(search_msg.nameSender, adressBook.me.name);
        /* Message contents (none) */
        search_msg.size = strlen(message)+1;
        search_msg.message = malloc(sizeof(char) * RAWSIZE);
        memset(search_msg.message, '\0', RAWSIZE);      
        strcpy(search_msg.message, message);
        
        printf("avant\n");
        addMsgReceived(search_msg); 
        printf("apres\n");
        
        /* For each contact ... */
        for (i=0; i<adressBook.nbContacts; i++)
        {
                printf("i = %d\n", i);
        
                Contact c = adressBook.contacts[i];
                
                printf("i2 = %d\n", i);
                
                if(c.connected)
                {
                        // Contact name
                        strcpy(search_msg.nameReceiver, name);
                
                        // Contact ip
                        strcpy(search_msg.ipReceiver, c.ip);

                        //send_message(search_msg);
                        printf("bluff send msg atteint\n");
                        pthread_t id;
                        printMessage(search_msg,"aa");
                        pthread_create (&id, NULL, send_message_thread,(void *)&search_msg);
                }
                
                printf("i3 = %d\n", i);
        }
        
        // Done !
}

